package com.whcoding.beetlsql.controller;

import com.whcoding.beetlsql.entity.OrmDeptVO;
import com.whcoding.beetlsql.service.OrmDeptService;
import org.apache.coyote.OutputBuffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-06-30 20:07
 **/
@RestController
@RequestMapping("/dept")
public class DeptController {

	@Autowired
	OrmDeptService ormDeptService;

	@PostMapping("/saveDept")
	public ResponseEntity saveDept(@RequestBody OrmDeptVO ormDeptVO) {
		OrmDeptVO deptVO = ormDeptService.saveDept(ormDeptVO);
		if (deptVO.getId() > 0) {
			// 添加数据成功，返回201
			return ResponseEntity.status(HttpStatus.CREATED).build();
		}
		// 执行失败或者发生异常，返回500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}


	@GetMapping("/deleteDept")
	public ResponseEntity deleteDept(Long deptId) {
		if (Objects.isNull(deptId)) {
			//参数没有或者格式错误，返回400
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
		}
		ormDeptService.deleteDept(deptId);
//		return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); 成功
//		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); 失败
		return ResponseEntity.ok().build();
	}

	@PostMapping("/updateDept")
	public ResponseEntity updateDept(@RequestBody OrmDeptVO ormDeptVO) {
		OrmDeptVO deptVO = ormDeptService.updateDept(ormDeptVO);
		if (deptVO.getId() > 0) {
			return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}

	/**
	 * http://localhost:11003/dept/getDeptList
	 * @return
	 */
	@GetMapping("/getDeptList")
	public ResponseEntity getDeptList() {
		try {
			List<OrmDeptVO> ormDeptVOS = ormDeptService.getDeptList();
			if (CollectionUtils.isEmpty(ormDeptVOS)) {
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
			}
			return ResponseEntity.ok(ormDeptVOS);
		} catch (Exception e) {
			e.getMessage();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}


}
